#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import matplotlib.pyplot as plt
import os
import numpy as np
import sys
# 这个代码打印只读、只写、真实读写混合，三种负载下，不同的trace里面的读操作加速情况
from plot2_iterationDecay import get_fmodelPctDecay_4dataName


def get_read_faster(filepath) -> float:
    with open(filepath) as f:
        lines = f.readlines()
    baseline_mean_all = -1
    llsm_mean_all = -1
    baseline_mean_read = -1
    llsm_mean_read = -1
    baseline_mean_write = -1
    llsm_mean_write = -1
    for line in lines:
        if "baseline_mean_read" in line:
            baseline_mean_read = float(line.split(' ')[-2])
        elif "llsm_mean_read" in line:
            llsm_mean_read = float(line.split(' ')[-2])

    if baseline_mean_read == -1:
        fasters = -1
    else:
        fasters = baseline_mean_read/llsm_mean_read
    return fasters


def get_read_faster_3workloads(filename):
    dataname = filename.split('.')[0]
    realRunpath = "../evaluation/expr_" + dataname + "_trace_realRun_16.txt"
    allGetpath = "../evaluation/expr_" + dataname + "_trace_allGet_16.txt"
    allPutpath = "../evaluation/expr_" + dataname + "_trace_allPut_16.txt"

    realRunFaster = get_read_faster(realRunpath)
    allGetFaster = get_read_faster(allGetpath)
    allPutFaster = get_read_faster(allPutpath)

    perf_fmodelPct_decay = get_fmodelPctDecay_4dataName(dataname, ["trace_allGet_16", "trace_allPut_16", "trace_realRun_16"], ['baseline', 'llsm'])
    first_num_fmodel = perf_fmodelPct_decay['trace_realRun_16']['llsm']['num_fmodel'][0]


    return realRunFaster, allGetFaster, allPutFaster, first_num_fmodel


def plot_filenames():
    perf_dict = dict()
    for filename in filenames:
        # [all read write]的faster其实是，平均后的
        realRunFaster, allGetFaster, allPutFaster, first_num_model = get_read_faster_3workloads(filename)
        perf_dict[filename] = dict({"realRun": realRunFaster, "allGet": allGetFaster, 'allPut': allPutFaster, 'first_num_model': first_num_model})

    keys = perf_dict.keys()
    realRunFasters = [perf_dict[key]['realRun'] for key in keys]
    allGetFasters = [perf_dict[key]['allGet'] for key in keys]
    allPutFasters = [perf_dict[key]['allPut'] for key in keys]
    first_num_models = [perf_dict[key]['first_num_model'] for key in keys]

    fig, ax1 = plt.subplots(figsize=(9, 7))
    plt.axhline(y=np.array(realRunFasters).mean(), ls='--', color='k', alpha=0.3)  # 与1比较，这里画出1
    plt.axhline(y=np.array(allGetFasters).mean(), ls='--', color='b', alpha=0.3)  # 与1比较，这里画出1
    plt.axhline(y=np.array(allPutFasters).mean(), ls='--', color='r', alpha=0.3)  # 与1比较，这里画出1

    plt.plot(realRunFasters, marker='d', label='realRunFasters', color='k')
    plt.plot(allGetFasters, marker='^', label='allGetFasters', color='b')
    plt.plot(allPutFasters, marker='v', label='allPutFasters', color='r')

    for i in range(len(realRunFasters)):
        plt.text(i, realRunFasters[i], "%.2f" % realRunFasters[i])
    for i in range(len(allGetFasters)):
        plt.text(i, allGetFasters[i], "%.2f" % allGetFasters[i])
    for i in range(len(allPutFasters)):
        plt.text(i, allPutFasters[i], "%.2f" % allPutFasters[i])
    ax1.legend(loc='center left')

    keys4label = [key.split('.')[0][:4] + '..' + key.split('.')[0][-4:] for key in keys]
    plt.xticks(range(len(keys)), keys4label, rotation=45)

    # sstable的数目有不同的刻度
    ax2 = ax1.twinx()
    ax2.plot(first_num_models, marker='o', label='first_num_models', color='gray', ls='--')
    for i in range(len(first_num_models)):
        plt.text(i, first_num_models[i], "%.0f" % first_num_models[i], color='gray')
    ax2.legend(loc='center right')

    title_ = filenames_path[17:] + ": " + str(len(filenames)) + "traces"
    plt.title(title_)
    # plt.ylim(0.6, 1.4)
    plt.savefig("../evaluation_group/Mean_Speedup_" + title_ + '.png')
    # plt.show()
    plt.close()


if __name__ == "__main__":
    # filenames_path = "picked_filenames_rdPct0.80_0.90__writeNum5M_80M_allNum10M_150M.txt"
    filenames_path = sys.argv[1]
    with open(filenames_path, 'r') as f:
        lines = f.readline()
    filenames = lines.split()
    # python main中的变量默认为全局变量
    plot_filenames()